<template>
  <div>
    <div class="head">
      微信扫码绑定账号
    </div>
    <wechat-login :loading="loading"
      :href="wx.href"
      :state="wx.state"
      :appid="wx.appid"
      :scope="wx.scope"
      self-redirect="true"
      :redirect-uri="wx.redirect_uri"
      @refresh="refresh"
      height="160px"
    />
  </div>
</template>

<script lang="ts">
import WechatLogin from "@/components/wechat-bind-code/index.vue";
import { getPartyParam } from '@/api/login'
import PsMessage from "@/components/message/index";
import { invokeAPi } from '@/xz-fn'
// @ts-ignore
import mixins from './bind-mixins'
export default {
  name: 'BindWx',
  components: {
    WechatLogin
  },
  mixins: [mixins],
  emits: ['code-done'],
  data () {
    return {
      loading: false,
      wx: {
        href: 'data:text/css;base64,LmltcG93ZXJCb3h7CiAgICBsaW5lLWhlaWdodDogMTsKfQoKLmltcG93ZXJCb3ggLnRpdGxlLAouaW1wb3dlckJveCAuaW5mbywKLnN0YXR1c19pY29uLAouaW1wb3dlckJveCAuc3RhdHVzIHtkaXNwbGF5OiBub25lO30KCi5pbXBvd2VyQm94IC5xcmNvZGUgewogICAgd2lkdGg6IDE2MHB4OwogICAgaGVpZ2h0OiAxNjBweDsKICAgIGJvcmRlcjogMDsKICAgIG1hcmdpbi10b3A6IDA7Cn0=',
        state: 'qekjdsbkje893214wechat',
        appid: '',
        scope: '',
        redirect_uri: encodeURI(import.meta.env.VITE_APP_CB_ORIGIN + '/party-login-cb.html?type=BindWxLoginFinish&skipInit=1'),
        style: 'black'
      }
    }
  },
  created () {
    this.getPartyParam()
    window.addEventListener("message", this.onMessage);
  },
  beforeUnmount () {
    window.removeEventListener("message", this.nMessage);
  },
  methods: {
    onMessage(msg: any) {
      if(msg.data?.type === "BindWxLoginFinish" && msg.data.code){
        this.bindWxLoginFinish({ code: msg.data.code });
      }
    },
    /**
     * 获取第三方登录参数
     */
    getPartyParam () {
      this.loading = true
      getPartyParam({ type: 'wx' }).then(res => {
        const data = res.data || {}
        this.wx.appid = data.appid
        this.wx.scope = data.scope
        this.loading = false
        setTimeout(() => {
          this.$emit('code-done')
        }, 1000)
      }).catch(e => {
        PsMessage.closeAll()
        this.loading = false
      })
    },
    /**
     * 刷新二维码
     */
    refresh () {
      this.getPartyParam()
    },
    /**
     * 获取第三方登录成功回调
     */
    bindWxLoginFinish ({ code }:any = {}) {
      const params = {
        auth_type: 'wx', // phone-绑定手机,wx-绑定微信
        phone: '', // 手机号码,auth_type=phone为必填
        auth_code: code, // 授权码或者手机验证码
        code_id: '', // 手机验证码对应id,只有授权类型为phone需要
        bind_type: 0, // 0-绑定，1-换绑
        old_phone: '',
        old_auth_code: '',
        old_code_id: '',
        version: 'v2'
      }
      this.onBindAuth(params, 'wx').then(() => {
      }).catch(() => {
        this.refresh()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// @import "@/theme/common/var";
.head {
  font-size: 18px;
  font-weight: 400;
  text-align: center;
}
</style>
